<template>
  <div class="project-container">
    <!-- 项目头部信息 -->
    <div class="project-header">
      <div class="project-title-row">
        <div class="project-title">
          <!-- 项目状态 -->
          <span class="project-badge">{{ project?.['686df6df33681903aca10690'] || '' }}</span>
          <!-- 项目名称 -->
          <h1>{{ project?.['686df5d4fa20ded33c042478'] || '' }}</h1>
        </div>
        <div class="title-actions">
          <!-- 客户名称 -->
          <span class="company-text">{{ getCustomer(project) }}</span>
          <button
            class="action-btn"
            :class="getRoleClass(value['686f2308f11e0126aeb367d7'])"
            v-for="value in uniqueRoleTypes"
            :key="value['686f2308f11e0126aeb367d7']"
          >
            {{ value['686f2308f11e0126aeb367d7'] }}
          </button>
        </div>
        <div class="right-actions">
          <button class="export-btn" @click="exportPDF">导出PDF</button>
        </div>
      </div>
      <div class="project-meta">
        <span class="project-info">
          <span class="project-item">{{
            getDate(project?.['686e317ee9211671b47589db'] || '')
          }}</span>
          <span class="project-item">|</span>
          <span class="project-item">
            {{
              diffDays({
                a: project?.['686e317ee9211671b47589db'] || '',
                b: project?.['686f5c562307310db1c4eea1'] || '',
              })
            }}
          </span>
          <span class="project-item" style="margin-left: 40px">{{
            project?.['6876ff515d31544df2c58975'] || ''
          }}</span>
        </span>
      </div>

      <!-- 分割线 -->
      <div class="divider"></div>

      <!-- 需求栏 -->
      <div class="requirements">
        <div class="req-left">
          <div class="req-roles">
            <span
              class="req-role"
              v-for="value in uniqueRoleTypes"
              :key="value['686f2308f11e0126aeb367d7']"
            >
              {{ value['686f2308f11e0126aeb367d7'] }} X{{ value['686e48ea1f42f2639e1b907b'] }}
            </span>
          </div>
          <span class="req-constraints"
            >要求：<span
              v-for="value in uniqueRoleTypes"
              :key="value['686f2308f11e0126aeb367d7']"
              >{{ getRequire(value['6880ba578c409b88b851aa8b']) }}</span
            ></span
          >
        </div>
        <div class="req-center">
          <span class="req-work"
            >工作内容：分为<span
              v-for="value in uniqueRoleTypes"
              :key="value['686f2308f11e0126aeb367d7']"
              >{{ value['686e48ea1f42f2639e1b907f'] }}、</span
            ></span
          >
        </div>
        <div class="req-right">
          <button class="recommend-btn" @click="selectRecommendedPersons">选择推荐人</button>
        </div>
      </div>
    </div>

    <!-- 标签导航 -->
    <div class="tab-navigation">
      <!-- 全部人员标签 -->
      <div
        v-if="visibleTabs.includes('all')"
        class="tab-item"
        :class="{ active: selectedClusterId === 'all' }"
        @click="selectCluster('all')"
      >
        <span class="tab-text">全部人员</span>
        <span class="tab-icon">📄</span>
      </div>

      <!-- 渲染群头名称 -->
      <div
        v-for="clusterName in visibleTabs.filter((tab) => tab !== 'all')"
        :key="clusterName"
        class="tab-item"
        :class="{ active: selectedClusterId === clusterName }"
        @click="selectCluster(clusterName)"
      >
        <span class="tab-text">{{ clusterName }}</span>
        <span class="tab-icon">📄</span>
      </div>

      <div class="tab-scroll-btn" @click="nextTabPage">
        <span class="tab-scroll-icon" aria-label="右箭头"></span>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-area">
      <!-- 左侧分类菜单 -->
      <div class="category-sidebar">
        <div
          v-for="roleType in uniqueRoleTypes"
          :key="roleType['686f2308f11e0126aeb367d7']"
          class="category-item"
          :class="{ active: selectedCategory === roleType['686f2308f11e0126aeb367d7'] }"
          @click="selectCategory(roleType['686f2308f11e0126aeb367d7'])"
        >
          <span class="category-text">{{ roleType['686f2308f11e0126aeb367d7'] }}</span>
        </div>
      </div>

      <!-- 右侧人员卡片区域 -->
      <div class="personnel-grid">
        <div
          v-for="person in filteredCandidateList"
          :key="person.rowid"
          class="personnel-card"
          @click="showRoleDetail(person['rowid'])"
        >
          <!-- 选择框 -->
          <div
            class="selection-mark"
            :class="{ selected: person.userSelected }"
            @click.stop="toggleSelection(person.rowid)"
          ></div>

          <!-- 已选择标签 -->
          <div v-if="person['68761720096a775fc5332e94'] == '已选中'" class="selected-label">
            已选择
          </div>

          <!-- 头像区域 -->
          <div class="avatar-container">
            <div
              class="avatar"
              :style="{
                backgroundImage: person['687633c7ef700e94a0d82b59']
                  ? `url(${JSON.parse(person['687633c7ef700e94a0d82b59'])[0]})`
                  : 'none',
              }"
            ></div>
            <div class="deal-badge">已成交{{ person['6875b364096a775fc5322bd7'] }}单</div>
          </div>

          <!-- 人员信息 -->
          <div class="personnel-info">
            <div class="name-section">
              <span class="name">{{ person['686e0c6fd9147824a38a6294'] }}</span>
              <span
                class="gender"
                :class="
                  person['686e0c6fd9147824a38a6295'] === '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf'
                    ? 'female'
                    : 'male'
                "
              >
                {{
                  person['686e0c6fd9147824a38a6295'] == '2d5e8f66-b757-4a60-b7e7-e7c2a3c716bf'
                    ? '♀'
                    : '♂'
                }}
              </span>
              <span class="location">
                {{ getProvinceAndCity(person['686e0f429104eb90ad4247a3']) }} ·
                {{
                  person['686e0f429104eb90ad4247a4'] === '470a70a3-4fc3-4c4c-bea6-3bd2a2b7556c'
                    ? '全国'
                    : '仅本地'
                }}
              </span>
            </div>

            <div class="stats">
              <div class="stat-item">
                <span class="stat-value">{{ person['686e0f429104eb90ad4247a5'] }}cm</span>
                <span class="stat-label">身高</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ person['686e0f429104eb90ad4247a6'] }}kg</span>
                <span class="stat-label">体重</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ person['688051358c409b88b8519759'] }}</span>
                <span class="stat-label">三围</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ person['686e0f429104eb90ad4247a8'] }}</span>
                <span class="stat-label">鞋码</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态提示 -->
        <div v-if="loading" class="loading-indicator">
          <p>正在加载数据...</p>
        </div>

        <!-- 初始加载状态提示 -->
        <div
          v-if="!loading && candidateList.length === 0 && detailsArr.length > 0"
          class="initial-loading-indicator"
        >
          <p>暂无角色数据</p>
        </div>

        <!-- 空状态提示 -->
        <div v-if="!loading && filteredCandidateList.length === 0" class="empty-indicator">
          <p>该群头暂无人员数据</p>
        </div>
      </div>
    </div>

    <!-- 角色详情弹框 -->
    <RoleDetailDialog v-model:visible="dialogVisible" :role-data="selectedRole" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { apiService, ApiService } from '@/utils/api'
import RoleDetailDialog from '@/components/RoleDetailDialog.vue'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { getAreaName, getProvinceAndCity } from '@/utils/areaCode'

// 获取路由参数
const route = useRoute()

// 获取用户状态管理实例
const userStore = useUserStore()

const demand = ref([])
const loading = ref(false) // 保留用于其他可能的加载状态
const candidateList = ref([]) // 存储候选人列表
const selectedClusterId = ref('all') // 当前选中的群头ID，'all'表示全部
const selectedCategory = ref('礼仪') // 当前选中的分类，默认礼仪

// 标签分页
const tabPageIndex = ref(0)
const tabsPerPage = 8 // 每页展示的群头数量（含"全部人员"占1）
const visibleTabs = computed(() => {
  // 创建包含"全部人员"和所有群头名称的列表
  const list = ['all', ...detailsArr.value.map((cluster) => cluster.clusterName)]
  const start = tabPageIndex.value * tabsPerPage
  const end = start + tabsPerPage
  return list.slice(start, end)
})

const nextTabPage = () => {
  const total = ['all', ...detailsArr.value.map((cluster) => cluster.clusterName)].length
  const maxPage = Math.max(0, Math.ceil(total / tabsPerPage) - 1)
  tabPageIndex.value = tabPageIndex.value >= maxPage ? 0 : tabPageIndex.value + 1
}

// const project = ref(route.query.project ? JSON.parse(route.query.project) : null)
const project = ref({})

// 弹框相关数据
const dialogVisible = ref(false)
const selectedRole = ref({})

const detailsArr = ref([])

const demandList = ref([])

const role = ref([])
const groupedDemand = ref({}) // 根据群头名称分组后的需求

// 计算属性：根据选中的群头和分类过滤候选人列表
const filteredCandidateList = computed(() => {
  // 直接返回candidateList，因为在selectCluster和selectCategory方法中
  // 已经根据当前选中的群头和分类获取了对应的候选人列表
  return candidateList.value
})

// 计算属性：去重后的角色类型列表
const uniqueRoleTypes = computed(() => {
  const uniqueRoles = []
  const seenRoles = new Set()

  demandList.value.forEach((item) => {
    const roleType = item['686f2308f11e0126aeb367d7']
    if (roleType && !seenRoles.has(roleType)) {
      seenRoles.add(roleType)
      uniqueRoles.push(item)
    }
  })

  return uniqueRoles
})

const getDemand = async () => {
  console.log('getDemand')

  const proRes = await apiService.getDemandList({
    // projectRowid: JSON.parse(route.query.project)['rowid'],
    projectRowid: route.query.id,
  })
  console.log('getDemandList')
  console.log(JSON.parse(proRes.data))
  demandList.value = JSON.parse(proRes.data)

  const registerRes = await apiService.getRoleRecord({
    projectName: project.value['686df5d4fa20ded33c042478'],
  })
  console.log('获取推荐记录')
  console.log(JSON.parse(registerRes.data))
  demand.value = JSON.parse(registerRes.data)

  // 按群头名称（字段：68773cef5d31544df2c5cfe0）进行分组
  groupedDemand.value = demand.value.reduce((acc, item) => {
    const groupName = item['68773cef5d31544df2c5cfe0'] || '未分组'
    if (!acc[groupName]) acc[groupName] = []
    acc[groupName].push(item)
    return acc
  }, {})
  console.log('按群头名称分组结果:', groupedDemand.value)
  console.log(groupedDemand.value[0])

  // 处理群头和角色数据
  detailsArr.value = [] // 清空之前的数据

  // 遍历所有群头
  for (const clusterName of Object.keys(groupedDemand.value)) {
    console.log(`群头名称: ${clusterName}`)
    console.log(`该群头下的需求数量: ${groupedDemand.value[clusterName].length}`)
    console.log(`该群头下的需求详情数组:`, groupedDemand.value[clusterName])
    console.log('角色分类数据')
    console.log(groupedDemand.value[clusterName][0]['68a80c640372283d1e925122'])
    console.log('角色数组数据')

    // 创建群头对象
    const clusterObj = {
      clusterName: clusterName,
      roleCategories: [], // 存储不同角色分类的数据
    }

    // 处理该群头下的所有角色分类
    const clusterDemands = groupedDemand.value[clusterName]

    // 收集该群头下的所有角色类型
    const roleTypes = new Set()
    clusterDemands.forEach((item) => {
      const roleType = item['68a80c640372283d1e925122'] // 角色分类字段
      if (roleType) {
        roleTypes.add(roleType)
      }
    })

    // 对每种角色类型处理角色数据
    for (const roleType of roleTypes) {
      // 找到该类型的需求数据
      const typeData = clusterDemands.find((item) => item['68a80c640372283d1e925122'] === roleType)
      if (!typeData) continue

      try {
        const roleList = JSON.parse(typeData['68b11046823eff0bd61326e4'] || '[]')
        console.log(`${roleType}角色数据:`, roleList)

        // 解析角色数据
        const parsedRoles = roleList
          .map((roleJson) => {
            try {
              return JSON.parse(roleJson)
            } catch (e) {
              console.error('解析角色JSON失败:', e)
              return null
            }
          })
          .filter(Boolean)

        // 添加到群头的角色分类中
        clusterObj.roleCategories.push({
          roleType: roleType,
          roleArray: parsedRoles,
        })
      } catch (error) {
        console.error(`解析${roleType}角色数据失败:`, error)
      }
    }

    // 将处理好的群头数据添加到数组
    detailsArr.value.push(clusterObj)
  }

  console.log('处理后的群头和角色数据:', detailsArr.value)

  // 初始化标签和分类
  if (detailsArr.value.length > 0) {
    // 设置默认选中的群头为第一个
    selectedClusterId.value = detailsArr.value[0].clusterName

    // 根据项目所需的角色类型设置默认分类
    if (uniqueRoleTypes.value.length > 0) {
      // 如果有"礼仪"分类就选择它，否则选择第一个项目所需的角色类型
      const hasCeremony = uniqueRoleTypes.value.find(
        (role) => role['686f2308f11e0126aeb367d7'] === '礼仪',
      )
      if (hasCeremony) {
        selectedCategory.value = '礼仪'
      } else {
        selectedCategory.value = uniqueRoleTypes.value[0]['686f2308f11e0126aeb367d7']
      }
    }
  }
}

const diffDays = (obj) => {
  // 把对象里的值取出来并转成 Date
  const [d1, d2] = Object.values(obj).map((v) => new Date(v))
  // 毫秒差 → 天数（向上取整，不足一天也算一天）
  const days = Math.ceil(Math.abs(d2 - d1) / (1000 * 60 * 60 * 24))
  return `${days}天`
}

// 选择群头标签
const selectCluster = async (clusterId) => {
  selectedClusterId.value = clusterId
  console.log('选中群头:', clusterId === 'all' ? '全部人员' : clusterId)

  // 清空候选人列表
  candidateList.value = []

  // 如果选择的是特定群头，获取对应的数据
  if (clusterId !== 'all') {
    const selectedCluster = detailsArr.value.find((cluster) => cluster.clusterName === clusterId)
    if (selectedCluster) {
      console.log('选中群头数据:', selectedCluster)
      console.log('群头名称:', selectedCluster.clusterName)
      console.log('当前选中分类:', selectedCategory.value)

      // 只显示当前选中分类对应的角色数据
      const currentCategoryData = selectedCluster.roleCategories.find(
        (roleCategory) => roleCategory.roleType === selectedCategory.value,
      )

      if (currentCategoryData) {
        console.log(`该群头下的${selectedCategory.value}数据:`, currentCategoryData.roleArray)
        console.log(`${selectedCategory.value}角色数量:`, currentCategoryData.roleArray.length)

        // 直接使用已获取的角色数据
        candidateList.value = currentCategoryData.roleArray.map((person) => ({
          ...person,
          userSelected: false,
        }))
        console.log('更新候选人列表:', candidateList.value.length)
      } else {
        console.log(`该群头下没有${selectedCategory.value}类型的角色`)
      }
    }
  } else {
    // 全部人员模式：获取所有群头的当前分类角色
    console.log('当前选择的是"全部人员"，显示所有群头的数据')

    // 收集所有群头中当前分类的角色
    const allRoles = []

    detailsArr.value.forEach((cluster) => {
      const categoryData = cluster.roleCategories.find(
        (category) => category.roleType === selectedCategory.value,
      )

      if (categoryData && categoryData.roleArray) {
        allRoles.push(...categoryData.roleArray)
      }
    })

    console.log(`所有群头的${selectedCategory.value}角色数量:`, allRoles.length)

    // 直接使用已获取的角色数据
    candidateList.value = allRoles.map((person) => ({
      ...person,
      userSelected: false,
    }))
    console.log('更新全部候选人列表:', candidateList.value.length)
  }

  console.log('过滤后的候选人数量:', filteredCandidateList.value.length)
}

const getDate = (str) => {
  if (!str) return ''
  const result = str.split(' ')[0].replace(/-/g, '.')
  return result
}

const getRequire = (item) => {
  // 安全检查：如果 item 不是数组或为空，返回空字符串
  if (!item || !Array.isArray(item) || item.length === 0) {
    return ''
  }

  const arr = []
  item.forEach((item) => {
    if (item == 'a8898a78-781d-4021-922d-556c6487eb23') {
      arr.push('五官端正')
    } else if (item == 'c724276d-24b9-4210-a143-edac3e5f1678') {
      arr.push('长相甜美')
    } else if (item == 'f39df266-786b-4cff-afd0-fddf7f15ba1e') {
      arr.push('170以上')
    } else if (item == 'b226cbaf-4c93-497c-bcbc-231ab011b28f') {
      arr.push('无纹身')
    } else if (item == '31acc45d-3cb2-4f89-90b6-9f8df1866f45') {
      arr.push('无美甲')
    } else if (item == '4cdb8dc2-2cb5-499b-b90f-5ed8873cf6f9') {
      arr.push('黑发')
    } else if (item == '14c46056-5ce6-4cf9-80b4-5c6b8c7b9f6e') {
      arr.push('标准普通话')
    } else if (item == '14c46056-5ce6-4cf9-80b4-5c6b8c7b9f6e') {
      arr.push('英语口语流利')
    } else if (item == 'other') {
      arr.push('其他')
    }
  })
  return arr.join('、')
}

const getRoleClass = (name) => {
  const map = {
    礼仪: 'ceremony',
    兼职: 'part-time',
    带队: 'team-lead',
  }
  return map[name] || ''
}

// 选择分类
const selectCategory = (category) => {
  selectedCategory.value = category
  console.log('选中分类:', category)
  console.log('当前筛选条件 - 群头:', selectedClusterId.value, '分类:', selectedCategory.value)

  // 重新调用selectCluster来更新数据，复用已有逻辑
  selectCluster(selectedClusterId.value)
}

//选择卡片
const toggleSelection = (personRowid) => {
  const person = candidateList.value.find((p) => p.rowid === personRowid)
  if (person) {
    person.userSelected = !person.userSelected
  }
}

const exportPDF = async () => {
  const selectedPersons = filteredCandidateList.value.filter((person) => person.userSelected)

  if (selectedPersons.length === 0) {
    console.log('⚠️ 没有选中任何人员')
    ElMessage.warning('请先选择要导出的人员')
    return
  }
  console.log('selectedPersons')

  console.log(selectedPersons)

  const pdfArr = selectedPersons.map((item) => ({
    name: item['686e0c6fd9147824a38a6294'],
    urldata: item['68a838270372283d1e9259e8'],
  }))
  console.log('pdfArr:', pdfArr)

  const pdfUrlArr = pdfArr
    .map((item) => {
      if (item.urldata) {
        try {
          const parsedData = JSON.parse(item.urldata)
          if (Array.isArray(parsedData) && parsedData.length > 0) {
            return {
              name: item.name,
              url: parsedData[0].DownloadUrl,
            }
          }
        } catch (error) {
          console.error('解析PDF数据失败:', error)
        }
      }
      return null
    })
    .filter(Boolean)

  console.log('pdfUrlArr:', pdfUrlArr)

  if (pdfUrlArr.length === 0) {
    console.log('⚠️ 没有找到可下载的PDF文件')
    ElMessage.warning('选中的人员没有可下载的PDF文件')
    return
  }

  // 批量下载PDF文件
  await downloadMultiplePDFs(pdfUrlArr)
}

// 批量下载多个PDF文件
const downloadMultiplePDFs = async (pdfData) => {
  try {
    console.log('开始批量下载PDF文件...')

    // 逐个下载PDF文件
    for (let i = 0; i < pdfData.length; i++) {
      const item = pdfData[i]
      const fileName = `${item.name || '未知姓名'}.pdf`

      console.log(`正在下载: ${fileName}`)

      try {
        // 使用直接链接下载（避免CORS问题）
        await downloadWithDirectLink(item.url, fileName)

        console.log(`✅ ${fileName} 下载完成`)

        // 添加延迟，避免浏览器阻止多个下载
        if (i < pdfData.length - 1) {
          await new Promise((resolve) => setTimeout(resolve, 500))
        }
      } catch (downloadError) {
        console.error(`下载 ${fileName} 失败:`, downloadError)
        ElMessage.warning(`${fileName} 下载失败，跳过此文件`)
      }
    }

    console.log('所有PDF文件下载完成！')

    // 显示成功提示
    ElMessage.success(`成功导出 ${pdfData.length} 个PDF文件！`)
  } catch (error) {
    console.error('PDF下载失败:', error)
    ElMessage.error('PDF下载失败，请重试')
  }
}

// 使用直接链接下载（避免CORS问题）
const downloadWithDirectLink = (url, fileName) => {
  return new Promise((resolve, reject) => {
    try {
      // 方法1: 尝试使用fetch + blob（如果CORS允许）
      fetch(url, { mode: 'no-cors' })
        .then((response) => {
          if (response.type === 'opaque') {
            // CORS仍然阻止，使用备用方案
            useFallbackMethod()
          } else {
            // CORS允许，使用blob下载
            return response.blob()
          }
        })
        .then((blob) => {
          if (blob) {
            // 创建下载链接
            const downloadUrl = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = downloadUrl
            link.download = fileName
            link.style.display = 'none'

            // 触发下载
            document.body.appendChild(link)
            link.click()

            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(downloadUrl)
            resolve()
          }
        })
        .catch(() => {
          // fetch失败，使用备用方案
          useFallbackMethod()
        })

      // 备用方案：使用iframe + 用户手动重命名
      const useFallbackMethod = () => {
        console.log(`使用备用方案下载: ${fileName}`)

        // 创建隐藏的iframe
        const iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.src = url

        // 监听iframe加载完成
        iframe.onload = () => {
          // 延迟后清理iframe
          setTimeout(() => {
            document.body.removeChild(iframe)

            // 提示用户手动重命名文件
            ElMessage.info(`文件已开始下载，请手动将文件名改为: ${fileName}`)
            resolve()
          }, 1000)
        }

        // 监听iframe加载错误
        iframe.onerror = () => {
          document.body.removeChild(iframe)
          reject(new Error('iframe加载失败'))
        }

        // 添加到DOM
        document.body.appendChild(iframe)
      }
    } catch (error) {
      reject(error)
    }
  })
}

//选择推荐人
const selectRecommendedPersons = async () => {
  const selectedPersons = filteredCandidateList.value.filter((person) => person.userSelected)

  console.log('登录用户 rowid:', userStore.userRowid)
  console.log(
    '选中角色的 rowid:',
    selectedPersons.map((p) => p.rowid),
  )

  if (selectedPersons.length === 0) {
    console.log('⚠️ 没有选中任何人员')
    ElMessage.warning('请先选择要推荐的人员')
    return
  }

  // 按角色类型分组
  const roleGroups = {
    ceremony: [], // 礼仪
    partTime: [], // 兼职
    teamLead: [], // 带队
  }

  // 根据当前选中的分类，将选中的人员添加到对应的角色组
  const currentCategory = selectedCategory.value
  console.log('当前选中的分类:', currentCategory)

  // 映射分类名称到英文键名
  let englishKey = ''
  if (currentCategory === '礼仪') englishKey = 'ceremony'
  else if (currentCategory === '兼职') englishKey = 'partTime'
  else if (currentCategory === '带队') englishKey = 'teamLead'

  if (englishKey && roleGroups[englishKey]) {
    // 将所有选中的人员添加到当前分类对应的角色组中
    selectedPersons.forEach((person) => {
      roleGroups[englishKey].push(person.rowid)
    })
  } else {
    console.log('⚠️ 无效的角色分类:', currentCategory)
    ElMessage.warning('无效的角色分类')
    return
  }

  console.log('按角色类型分组的结果:', roleGroups)

  try {
    // 一次性提交所有角色分组数据
    console.log('正在提交角色分组数据:', roleGroups)

    console.log('提交数据:', {
      roleGroups: roleGroups, // 传递角色分组对象
      projectRowid: project.value['rowid'],
      userRowid: userStore.userRowid,
    })

    const result = await apiService.selectRole({
      roleGroups: roleGroups, // 传递角色分组对象
      projectRowid: project.value['rowid'],
      userRowid: userStore.userRowid,
    })

    console.log('角色提交结果:', result)
    ElMessage.success('推荐人员提交成功！')
  } catch (error) {
    console.error('提交推荐人员失败:', error)
    ElMessage.error('提交失败，请重试')
  }
}

// 显示角色详情
const showRoleDetail = (personRowid) => {
  selectedRole.value = personRowid
  dialogVisible.value = true
}

const getCustomer = (project) => {
  const customerData = project?.['686f297f781faa1ac7bbda20']
  if (customerData === '[]') {
    return ''
  }

  try {
    const parsedData = JSON.parse(customerData)
    const sourceValue = JSON.parse(parsedData[0].sourcevalue)
    return sourceValue['686f26e30323e30ac5121f7e'] || ''
  } catch (error) {
    return ''
  }
}

const getProject = async () => {
  const projectId = route.query.id
  if (projectId) {
    const result = await apiService.getRowById({
      rowId: route.query.id,
      worksheetId: ApiService.WORKSHEETENUM.PROJECTS,
    })
    console.log('getProject:', result)
    project.value = result
  }
}

onMounted(async () => {
  console.log('页面加载完毕')

  // 打印路由参数
  console.log('项目对象:', route.query.project ? JSON.parse(route.query.project) : null)
  console.log('项目对象id:', route.query.id)

  await getProject()

  await getDemand()

  // 初始化选中第一个群头和分类
  if (detailsArr.value.length > 0) {
    selectCluster(selectedClusterId.value)
  }
})
</script>

<style scoped>
.location {
  color: #919090;
  font-size: 12px;
  margin-left: 10px;
}

.project-container {
  padding: 20px;
  background: #ffffff;
  height: 100vh;
  font-family: 'Microsoft YaHei', sans-serif;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-width: 1600px;
  margin: 0 auto;
}

/* 项目头部信息 */
.project-header {
  border-bottom: none;
  background-color: #f8f7fd;
  padding: 20px;
  border-radius: 10px;
}

.project-title-row {
  display: flex;
  align-items: flex-end;
  margin-bottom: 8px;
  gap: 20px;
  width: 100%;
}

.project-title {
  display: flex;
  align-items: center;
  gap: 15px;
}

.project-badge {
  background: #ff8800;
  color: white;
  padding: 4px 16px;
  border-radius: 4px;
  font-size: 16px;
}

.project-title h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
  font-weight: 600;
  max-width: 400px; /* 固定宽度 */
  white-space: nowrap; /* 防止换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  font-size: clamp(16px, 4vw, 24px); /* 响应式字体大小，最小16px，最大24px */
}

.project-meta {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
  line-height: 1;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: nowrap;
}

.title-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: nowrap;
  position: relative;
  top: 5px;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.title-actions::-webkit-scrollbar {
  display: none;
}

.company-text {
  color: #949496;
  font-size: 14px;
}

.divider {
  height: 1px;
  background-color: #dbdadf;
  margin: 20px 20px;
}

.requirements {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 20px;
}

.req-left {
  display: flex;
  flex: 1 1 0;
  min-width: 0;
  flex-direction: column;
  gap: 8px;
}

.req-roles {
  display: flex;
  align-items: center;
  gap: 12px;
}

.req-role {
  color: #333;
  font-size: 14px;
}

.req-constraints {
  color: #666;
  font-size: 13px;
  display: inline-block;
  max-width: 39ch;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.req-center {
  flex: 1 1 0;
  min-width: 0;
  display: flex;
  align-items: center;
  color: #666;
  font-size: 13px;
}
.req-work {
  max-width: 43ch;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.req-right {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-end;
  align-self: stretch;
  flex: 1 1 0;
  min-width: 0;
}

.right-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-items: flex-end;
  margin-left: auto;
}

.action-btn {
  padding: 8px 18px;
  border: none;
  background: white;
  border-radius: 20px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #ddd;
  white-space: nowrap;
  min-width: fit-content;
  flex-shrink: 0;
}

.action-btn:hover {
  border-color: #ff69b4;
  color: #ff69b4;
}

/* 特定类型按钮样式 */
.action-btn.ceremony {
  background: #fddbec;
  border: none;
  color: #333;
}

.action-btn.part-time {
  background: #dbe9fb;
  border: none;
  color: #333;
}
.project-item {
  color: #eb4498;
  font-weight: 800;
}

.action-btn.team-lead {
  background: #fbe5dc;
  border: none;
  color: #333;
}

.export-btn {
  padding: 6px 16px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
}

.recommend-btn {
  padding: 6px 16px;
  background: #ea4096;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.recommend-btn:hover {
  background: #e55aa0;
}

/* 标签导航 */
.tab-navigation {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 20px;
  overflow-x: auto;
  padding-bottom: 5px;
  margin-top: 30px;
  scrollbar-width: thin;
  scrollbar-color: #ddd transparent;
}

.tab-navigation::-webkit-scrollbar {
  height: 4px;
}

.tab-navigation::-webkit-scrollbar-track {
  background: transparent;
}

.tab-navigation::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}

.tab-scroll-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

.tab-scroll-icon {
  width: 16px;
  height: 16px;
  display: inline-block;
  background-color: #c2c2c2;
  mask-image: url('@/assets/images/右箭头.svg');
  -webkit-mask-image: url('@/assets/images/右箭头.svg');
  mask-size: contain;
  -webkit-mask-size: contain;
  mask-repeat: no-repeat;
  -webkit-mask-repeat: no-repeat;
  mask-position: center;
  -webkit-mask-position: center;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #f5f5f5;
  border-radius: 20px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.tab-item.active {
  background: #ff69b4;
  color: white;
}

.tab-item:hover:not(.active) {
  background: #ebebeb;
}

.tab-icon {
  font-size: 12px;
}

/* 主要内容区域 */
.content-area {
  background-color: #fdf3f4;
  display: flex;
  gap: 20px;
  flex: 1;
  overflow: hidden;
}

/* 左侧分类菜单 */
.category-sidebar {
  width: 40px;
  flex-shrink: 0;
  background: linear-gradient(to bottom, #e8e4f0 0%, #eddbe7 50%, #fae6e9 100%);
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  padding: 20px 0;
  height: 100%;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-top: 30px;
}

.category-item:hover {
  background: rgba(255, 255, 255, 0.2);
}

.category-item.active .category-text {
  color: #000;
}

.category-text {
  writing-mode: vertical-rl;
  text-orientation: mixed;
  font-size: 14px;
  color: #999999;
  font-weight: 500;
  letter-spacing: 2px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 人员卡片网格 */
.personnel-grid {
  background-color: #fdf3f4;
  flex: 1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: max-content;
  gap: 20px;
  padding: 12px;
  overflow-y: auto;
  height: 100%;
  align-content: start;
  /* 隐藏滚动条但保持滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

/* 隐藏Webkit浏览器的滚动条 */
.personnel-grid::-webkit-scrollbar {
  display: none;
}

/* 已选择标签 */
.selected-label {
  position: absolute;
  top: 0;
  left: 0;
  background: #eb4196;
  color: white;
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 8px 0 0 0;
  z-index: 3;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(235, 65, 150, 0.3);
  transition: opacity 0.3s ease;
}

.personnel-card {
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: visible;
  transition: all 0.3s ease;
  position: relative;
  cursor: pointer;
}

.personnel-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: #f28ec0;
}

/* 选择框 - 定位到右上角边框上 */
.selection-mark {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid #ddd;
  background: white;
  z-index: 2;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.selection-mark.selected {
  background: #ff69b4;
  border-color: #ff69b4;
}

.selection-mark.selected::after {
  content: '✓';
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.avatar-container {
  position: relative;
  padding: 15px 15px 10px;
}

/* 正方形头像 */
.avatar {
  width: 100%;
  aspect-ratio: 1;
  border-radius: 6px;
  background: linear-gradient(135deg, #f5f5f5 0%, #e8e8e8 100%);
  background-size: cover;
  background-position: center;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
}

/* 占位符头像样式 */
.avatar:not([style*='url'])::before {
  content: '👤';
  font-size: 40px;
  color: #ccc;
  opacity: 0.8;
}

.avatar:not([style*='url'])::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% {
    left: -100%;
  }
  100% {
    left: 100%;
  }
}

.deal-badge {
  position: absolute;
  bottom: 4px;
  right: 4px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #eb4196;
  background: rgba(255, 255, 255, 0.9);
  white-space: nowrap;
  backdrop-filter: blur(4px);
}

.personnel-info {
  padding: 0 15px 15px;
}

.name-section {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.gender {
  font-size: 14px;
  color: #ff69b4;
  font-weight: 900;
}

.stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 4px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 11px;
  color: #333;
  font-weight: 500;
  margin-bottom: 2px;
}

.stat-label {
  display: block;
  font-size: 10px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .personnel-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 1200px) {
  .personnel-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .project-title-row {
    flex-wrap: wrap;
    gap: 15px;
  }

  .title-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
}

@media (max-width: 900px) {
  .content-area {
    flex-direction: column;
  }

  .category-sidebar {
    width: 100%;
  }

  .personnel-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .project-title-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .project-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .title-actions {
    flex-direction: row;
    align-items: center;
    gap: 8px;
    width: 100%;
    overflow-x: auto;
    padding-bottom: 5px;
  }

  .right-actions {
    align-items: flex-start;
    margin-left: 0;
  }

  .requirements {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .req-left,
  .req-center,
  .req-right {
    width: 100%;
  }

  .req-constraints,
  .req-work {
    max-width: 100%;
    white-space: normal;
  }
}

@media (max-width: 600px) {
  .personnel-grid {
    grid-template-columns: 1fr;
  }

  .project-header {
    padding: 15px;
  }

  .project-title h1 {
    font-size: 20px;
    width: 300px; /* 小屏幕下的固定宽度 */
    font-size: clamp(14px, 3.5vw, 20px); /* 响应式字体大小 */
  }

  .project-badge {
    font-size: 14px;
    padding: 3px 12px;
  }

  .action-btn {
    padding: 6px 14px;
    font-size: 13px;
    min-width: auto;
  }

  .export-btn,
  .recommend-btn {
    padding: 5px 12px;
    font-size: 12px;
  }

  .tab-navigation {
    margin-top: 20px;
    gap: 3px;
  }

  .tab-item {
    padding: 8px 12px;
    font-size: 13px;
  }

  .title-actions {
    gap: 6px;
  }

  .company-text {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .project-title-row {
    gap: 12px;
  }

  .title-actions {
    gap: 5px;
    padding-bottom: 3px;
  }

  .action-btn {
    padding: 5px 12px;
    font-size: 12px;
  }

  .company-text {
    font-size: 12px;
  }
}

/* 加载状态样式 */
.loading-indicator,
.initial-loading-indicator,
.no-more-indicator,
.empty-indicator {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.loading-indicator p {
  margin: 0;
  color: #ff69b4;
}

.initial-loading-indicator p {
  margin: 0;
  color: #ff69b4;
  font-weight: 500;
}

.no-more-indicator p {
  margin: 0;
  color: #999;
}

.empty-indicator p {
  margin: 0;
  color: #ccc;
}
</style>
